﻿// Partial Copyright (c) LogoUI Software Solutions LTD
// Author: Vladislav Spivak
// This source file is the part of LogoFX Framework http://logofx.codeplex.com
// See accompanying licences and credits.

//CompositionInitializer that does not hold on to parts by default
//based on, but not limited to http://codepaste.net/mo7afq (G-d bless Glen Block...)


#if SILVERLIGHT

using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Primitives;
using System.ComponentModel.Composition.Hosting;

namespace Microsoft.ComponentModel.Composition
{
    public static class CompositionInitializerEx
    {
        public static void SatisfyImports(ComposablePart part, bool allowRecomposition = false)
        {
            var container = Hosting.CompositionHostEx.GetContainer();
            if (allowRecomposition)
                CompositionInitializer.SatisfyImports(part);

            container.SatisfyImportsOnce(part);
        }

        public static void SatisfyImports(object attributedPart, bool allowRecomposition = false)
        {
            var container = Hosting.CompositionHostEx.GetContainer();
            if (allowRecomposition)
                CompositionInitializer.SatisfyImports(attributedPart);

            container.SatisfyImportsOnce(attributedPart);
        }

    }

    namespace Hosting
    {
        public static class CompositionHostEx
        {
            private static CompositionContainer _container;
            public static CompositionContainer GetContainer()
            {
                if (_container == null)
                {
                    throw new InvalidOperationException("Initialize has not been called on CompositionInitializer");
                }
                return _container;
            }

            public static void Initialize()
            {
                Initialize(new DeploymentCatalog());
            }

            public static void Initialize(CompositionContainer container)
            {
                CompositionHost.Initialize(container);
                _container = container;
            }

            public static void Initialize(params ComposablePartCatalog[] catalogs)
            {
                var catalog = new AggregateCatalog(catalogs);
                var container = new CompositionContainer(catalog);
                Initialize(container);
            }
        }
    }
}
#endif